package com.sanqing.iframe;

import com.sanqing.model.Operator;
import com.sanqing.dao.Dao;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.MouseInputAdapter;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class 	UserModFrame extends JInternalFrame {
    private JTextField isbnQueryField;
    private JButton queryButton;
    private JTable table;
    private DefaultTableModel tableModel;
    private String[] columnNames = {"读者编号", "姓名", "性别", "年龄", "证件号码", "有效期", "证件类型", "电话号码"};
    private Map<String, Operator> operatorMap = new HashMap<>();
    private JTextField isbnField, nameField, identityField, telField;
    private JComboBox<String> sexCombo, typeCombo;
    private JSpinner ageSpinner;
    private JFormattedTextField dateField;
    private JPasswordField passwordField, confirmPasswordField;

    private static final Map<Integer, String> ID_TYPE_MAP = new HashMap<>();
    private static final Map<Integer, Integer> MAX_BORROW_MAP = new HashMap<>();
    static {
        ID_TYPE_MAP.put(1, "本科生");
        ID_TYPE_MAP.put(2, "研究生");
        ID_TYPE_MAP.put(3, "教职工");
        MAX_BORROW_MAP.put(1, 5);
        MAX_BORROW_MAP.put(2, 10);
        MAX_BORROW_MAP.put(3, 20);
    }

    public UserModFrame() {
        super("管理员信息修改与删除", true, true, true, true);
        setSize(800, 600);
        setLayout(new BorderLayout());
        setBounds(20, 50, 850, 550);
        // 查询面板
        JPanel queryPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        JLabel queryLabel = new JLabel("读者编号查询：");
        isbnQueryField = new JTextField(15);
        queryButton = new JButton("查询");
        queryButton.addActionListener(new QueryActionListener());
        queryPanel.add(queryLabel);
        queryPanel.add(isbnQueryField);
        queryPanel.add(queryButton);
        add(queryPanel, BorderLayout.NORTH);

        // 表格面板
        tableModel = new DefaultTableModel(null, columnNames);
        table = new JTable(tableModel) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false; // 所有单元格都不可编辑
            }
        };
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane, BorderLayout.CENTER);

        // 操作面板（修改、删除）
        JPanel operationPanel = new JPanel(new GridLayout(6, 2, 10, 10));
        operationPanel.setBorder(new EmptyBorder(20, 20, 20, 20));

        // 读者编号（修改时显示，不可编辑） & 姓名
        JPanel isbnAndNamePanel = new JPanel(new GridLayout(1, 2, 10, 10));
        JLabel isbnLabel = new JLabel("读者编号：");
        isbnField = new JTextField();
        isbnField.setEditable(false);
        JLabel nameLabel = new JLabel("姓名：");
        nameField = new JTextField();
        isbnAndNamePanel.add(isbnLabel);
        isbnAndNamePanel.add(isbnField);
        isbnAndNamePanel.add(nameLabel);
        isbnAndNamePanel.add(nameField);
        operationPanel.add(isbnAndNamePanel);

        // 性别 & 年龄
        JPanel sexAndAgePanel = new JPanel(new GridLayout(1, 2, 10, 10));
        JLabel sexLabel = new JLabel("性别：");
        sexCombo = new JComboBox<>(new String[]{"男", "女"});
        JLabel ageLabel = new JLabel("年龄：");
        ageSpinner = new JSpinner(new SpinnerNumberModel(18, 1, 100, 1));
        sexAndAgePanel.add(sexLabel);
        sexAndAgePanel.add(sexCombo);
        sexAndAgePanel.add(ageLabel);
        sexAndAgePanel.add(ageSpinner);
        operationPanel.add(sexAndAgePanel);

        // 证件号码 & 有效期
        JPanel identityAndDatePanel = new JPanel(new GridLayout(1, 2, 10, 10));
        JLabel identityLabel = new JLabel("证件号码：");
        identityField = new JTextField();
        identityField.setDocument(new NumberDocument(10));
        JLabel dateLabel = new JLabel("有效期（yyyy-MM-dd）：");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateField = new JFormattedTextField(dateFormat);
        identityAndDatePanel.add(identityLabel);
        identityAndDatePanel.add(identityField);
        identityAndDatePanel.add(dateLabel);
        identityAndDatePanel.add(dateField);
        operationPanel.add(identityAndDatePanel);

        // 证件类型 & 电话号码
        JPanel typeAndTelPanel = new JPanel(new GridLayout(1, 2, 10, 10));
        JLabel typeLabel = new JLabel("证件类型：");
        typeCombo = new JComboBox<>(ID_TYPE_MAP.values().toArray(new String[0]));
        JLabel telLabel = new JLabel("电话号码：");
        telField = new JTextField();
        telField.setDocument(new NumberDocument(11));
        typeAndTelPanel.add(typeLabel);
        typeAndTelPanel.add(typeCombo);
        typeAndTelPanel.add(telLabel);
        typeAndTelPanel.add(telField);
        operationPanel.add(typeAndTelPanel);

        // 密码 & 确认密码
        JPanel passwordAndConfirmPanel = new JPanel(new GridLayout(1, 2, 10, 10));
        JLabel passwordLabel = new JLabel("密码：");
        passwordField = new JPasswordField();
        JLabel confirmPasswordLabel = new JLabel("确认密码：");
        confirmPasswordField = new JPasswordField();
        passwordAndConfirmPanel.add(passwordLabel);
        passwordAndConfirmPanel.add(passwordField);
        passwordAndConfirmPanel.add(confirmPasswordLabel);
        passwordAndConfirmPanel.add(confirmPasswordField);
        operationPanel.add(passwordAndConfirmPanel);
        
        table.getColumnModel().getColumn(4).setPreferredWidth(120); // 扩大类别名称列宽
        table.getColumnModel().getColumn(5).setPreferredWidth(120); // 扩大类别名称列宽
        table.getColumnModel().getColumn(7).setPreferredWidth(150); // 扩大类别名称列宽
        scrollPane.setViewportView(table);

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        JButton updateButton = new JButton("修改");
        updateButton.addActionListener(new UpdateActionListener());
        JButton deleteButton = new JButton("删除");
        deleteButton.addActionListener(new DeleteActionListener());
        JButton closeButton = new JButton("关闭");
        closeButton.addActionListener(e -> dispose());
        buttonPanel.add(updateButton);
        buttonPanel.add(deleteButton);
        buttonPanel.add(closeButton);
        operationPanel.add(buttonPanel);
        add(operationPanel, BorderLayout.SOUTH);

        // 表格行点击事件
        table.addMouseListener(new TableClickListener());

        // 初始加载全部数据
        loadData(null);
    }

    private void loadData(String isbn) {
        tableModel.setRowCount(0);
        operatorMap.clear();
        String sql = "SELECT R_ISBN, name, sex, age, identityCard, date, zj, tel, password, admin " +
                "FROM tb_operator WHERE admin = 1";
        if (isbn != null && !isbn.isEmpty()) {
            sql += " AND R_ISBN = '" + isbn + "'";
        }
        ResultSet rs = Dao.executeQuery(sql);
        try {
            while (rs.next()) {
                Operator op = new Operator();
                op.setISBN(rs.getString("R_ISBN"));
                op.setName(rs.getString("name"));
                op.setSex(rs.getString("sex"));
                op.setAge(rs.getString("age"));
                op.setIndentityCard(rs.getString("identityCard"));
                op.setDate(rs.getDate("date"));
                op.setZj(rs.getInt("zj"));
                op.setTel(rs.getString("tel"));
                op.setPassword(rs.getString("password"));
                op.setGrade(rs.getInt("admin")); // 读取等级字段
                operatorMap.put(op.getISBN(), op);
                Object[] row = {
                        op.getISBN(),
                        op.getName(),
                        op.getSex(),
                        op.getAge(),
                        op.getIndentityCard(),
                        rs.getDate("date") != null ? new SimpleDateFormat("yyyy-MM-dd").format(rs.getDate("date")) : "",
                        ID_TYPE_MAP.get(op.getZj()),
                        op.getTel()
                };
                tableModel.addRow(row);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (rs != null) rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    private class QueryActionListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            String isbn = isbnQueryField.getText().trim();
            if (!isbn.isEmpty()) {
                // 先校验查询的用户等级是否为1
                Operator op = checkOperatorLevel(isbn);
                if (op != null && "0".equals(op.getGrade())) { // 等级为1时禁止查询
                    JOptionPane.showMessageDialog(UserModFrame.this, "非管理员账号", "权限错误", JOptionPane.ERROR_MESSAGE);
                    tableModel.setRowCount(0); // 清空表格
                    clearForm(); // 清空表单
                    return;
                }
            }
            loadData(isbn); // 执行带等级过滤的查询
        }
    }

    private class TableClickListener extends MouseInputAdapter {
        @Override
        public void mouseClicked(java.awt.event.MouseEvent e) {
            int row = table.getSelectedRow();
            if (row != -1) {
                String isbn = (String) tableModel.getValueAt(row, 0);
                Operator op = operatorMap.get(isbn);
                // 点击行时再次校验等级（防止缓存数据异常）
                if ("0".equals(op.getGrade())) {
                    JOptionPane.showMessageDialog(UserModFrame.this, "非管理员账号", "权限错误", JOptionPane.ERROR_MESSAGE);
                    clearForm();
                    return;
                }
                // 填充表单
                fillForm(op);
            }
        }
    }

    private class UpdateActionListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            String isbn = isbnField.getText().trim();
            if (isbn.isEmpty()) {
                JOptionPane.showMessageDialog(UserModFrame.this, "请选择要修改的记录", "提示", JOptionPane.INFORMATION_MESSAGE);
                return;
            }
            Operator op = operatorMap.get(isbn);
            if (op == null) {
                JOptionPane.showMessageDialog(UserModFrame.this, "记录已失效，请重新查询", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }
            if ("0".equals(op.getGrade())) { // 修改前校验等级
                JOptionPane.showMessageDialog(UserModFrame.this, "非管理员账号", "权限错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            String name = nameField.getText().trim();
            String sex = (String) sexCombo.getSelectedItem();
            int age = (int) ageSpinner.getValue();
            String identity = identityField.getText().trim();
            String dateStr = dateField.getText().trim();
            int type = typeCombo.getSelectedIndex() + 1;
            String tel = telField.getText().trim();
            String password = new String(passwordField.getPassword());
            String confirmPassword = new String(confirmPasswordField.getPassword());

            // 校验逻辑
            if (name.isEmpty() || identity.isEmpty() || dateStr.isEmpty() || tel.isEmpty() || password.isEmpty() || confirmPassword.isEmpty()) {
                JOptionPane.showMessageDialog(UserModFrame.this, "所有字段都必须填写", "输入错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            if (!password.equals(confirmPassword)) {
                JOptionPane.showMessageDialog(UserModFrame.this, "两次密码不一致", "输入错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            if (!identity.matches("\\d{10}") || !tel.matches("\\d{11}")) {
                JOptionPane.showMessageDialog(UserModFrame.this, "证件号码或电话格式错误", "输入错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            Date date;
            try {
                date = new SimpleDateFormat("yyyy-MM-dd").parse(dateStr);
            } catch (ParseException ex) {
                JOptionPane.showMessageDialog(UserModFrame.this, "日期格式错误", "输入错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            // 更新SQL（需确保Dao支持参数化，此处假设已修改）
            String sql = "UPDATE tb_operator SET name=?, sex=?, age=?, identityCard=?, date=?, zj=?, tel=?, password=? WHERE R_ISBN=?";
            int result = Dao.executeUpdate(sql, name, sex, age, identity, new java.sql.Date(date.getTime()), type, tel, password, isbn);
            table.getColumnModel().getColumn(4).setPreferredWidth(120); // 扩大类别名称列宽
            table.getColumnModel().getColumn(5).setPreferredWidth(120); // 扩大类别名称列宽
            table.getColumnModel().getColumn(7).setPreferredWidth(150); // 扩大类别名称列宽
            if (result > 0) {
                JOptionPane.showMessageDialog(UserModFrame.this, "修改成功", "提示", JOptionPane.INFORMATION_MESSAGE);
                loadData(isbnQueryField.getText().trim()); // 重新加载数据
            } else {
                JOptionPane.showMessageDialog(UserModFrame.this, "修改失败", "提示", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    private class DeleteActionListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            int row = table.getSelectedRow();
            if (row != -1) {
                String isbn = (String) tableModel.getValueAt(row, 0);
                Operator op = operatorMap.get(isbn);
                if ("0".equals(op.getGrade())) { // 删除前校验等级
                    JOptionPane.showMessageDialog(UserModFrame.this, "非管理员账号", "权限错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }
                int confirm = JOptionPane.showConfirmDialog(UserModFrame.this, "确定删除该记录？", "确认删除", JOptionPane.YES_NO_OPTION);
                if (confirm == JOptionPane.YES_OPTION) {
                    String sql = "DELETE FROM tb_operator WHERE R_ISBN=?";
                    int result = Dao.executeUpdate(sql, isbn);
                    table.getColumnModel().getColumn(4).setPreferredWidth(120); // 扩大类别名称列宽
                    table.getColumnModel().getColumn(5).setPreferredWidth(120); // 扩大类别名称列宽
                    table.getColumnModel().getColumn(7).setPreferredWidth(150); // 扩大类别名称列宽
                    if (result > 0) {
                        JOptionPane.showMessageDialog(UserModFrame.this, "删除成功", "提示", JOptionPane.INFORMATION_MESSAGE);
                        loadData(isbnQueryField.getText().trim()); // 重新加载数据
                    } else {
                        JOptionPane.showMessageDialog(UserModFrame.this, "删除失败", "提示", JOptionPane.ERROR_MESSAGE);
                    }
                }
            } else {
                JOptionPane.showMessageDialog(UserModFrame.this, "请选择要删除的记录", "提示", JOptionPane.INFORMATION_MESSAGE);
            }
        }
    }

    private Operator checkOperatorLevel(String isbn) {
        String sql = "SELECT admin FROM tb_operator WHERE R_ISBN = ?";
        ResultSet rs = Dao.executeQuery(sql, isbn);
        try {
            if (rs.next()) {
                Operator op = new Operator();
                op.setGrade(rs.getInt("admin"));
                return op;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
        }
        return null;
    }

    // 清空表单
    private void clearForm() {
        isbnField.setText("");
        nameField.setText("");
        sexCombo.setSelectedIndex(0);
        ageSpinner.setValue(18);
        identityField.setText("");
        dateField.setValue(null);
        typeCombo.setSelectedIndex(0);
        telField.setText("");
        passwordField.setText("");
        confirmPasswordField.setText("");
    }

    private void fillForm(Operator op) {
        isbnField.setText(op.getISBN());
        nameField.setText(op.getName() != null ? op.getName() : "");
        sexCombo.setSelectedItem(op.getSex() != null ? op.getSex() : "男"); // 默认选中"男"
        
        // 年龄处理（转为整数并设置到Spinner）
        try {
            ageSpinner.setValue(Integer.parseInt(op.getAge()));
        } catch (NumberFormatException e) {
            ageSpinner.setValue(18); // 年龄解析失败时默认18岁
        }
        
        identityField.setText(op.getIndentityCard() != null ? op.getIndentityCard() : "");
        
        // 日期处理（格式化日期显示）
        if (op.getDate() != null) {
            dateField.setValue(new Date(op.getDate().getTime()));
        } else {
            dateField.setValue(null);
        }
        
        // 证件类型处理（根据数据库存储的zj值匹配下拉框选项）
        Integer zjValue = op.getZj();
        if (zjValue != null && ID_TYPE_MAP.containsValue(zjValue)) {
            // 根据值获取对应的证件类型文本
            for (Map.Entry<Integer, String> entry : ID_TYPE_MAP.entrySet()) {
                if (entry.getKey().equals(zjValue)) {
                    typeCombo.setSelectedItem(entry.getValue());
                    break;
                }
            }
        } else {
            typeCombo.setSelectedIndex(0); // 默认选中第一个选项
        }
        
        telField.setText(op.getTel() != null ? op.getTel() : "");
        
        // 密码框处理
        String password = op.getPassword();
        if (password != null && !password.isEmpty()) {
            passwordField.setText(password);
            confirmPasswordField.setText(password); // 确保两次密码一致
        } else {
            passwordField.setText("");
            confirmPasswordField.setText("");
        }
    }
    private class NumberDocument extends javax.swing.text.PlainDocument {
        private int maxLength;

        public NumberDocument(int maxLength) {
            this.maxLength = maxLength;
        }

        @Override
        public void insertString(int offs, String str, javax.swing.text.AttributeSet a) throws javax.swing.text.BadLocationException {
            if (str == null) return;
            if ((getLength() + str.length()) <= maxLength && str.matches("\\d*")) {
                super.insertString(offs, str, a);
            }
        }
    }
    
}